<template>
    <Card>
        <!--按照类型搜索-->
        <!-- <Select v-model="type" style="width:30%" @on-change="getData(true)" :placeholder="'请选择类型'">
            <Option v-for="item in codes" :value="item.value" :key="item.value">{{ item.name }}</Option>
        </Select> -->

        <!-- 按照时间搜索 -->
        <!-- <DatePicker 
            type="daterange" 
            placeholder="请选择时间段" 
            style="width: 30%;margin-right:10px" 
            v-model="timeRange">
        </DatePicker> -->

        <!-- <Button type="primary" icon="ios-search" @click="getData(true)">搜索</Button>	 -->
        <Button type="primary" @click="show = true" shape="circle" style="float: right;">新增功能码</Button>	

        <div style="padding: 70px 0 0;">
            <Table stripe border :columns="columns" :data="datas" size="small" :loading="tableIsLoadig"></Table>
        </div>

        <Page :total="total" 
        :page-size="size" 
        show-elevator
        :current.sync="page" 
        show-total style="text-align:center"
        :class-name="'page'"></Page>
        

        <Modal
            title="功能码授权"
            :value="show"
            width="800"
            @on-visible-change="(showState) => this.show = showState"
            @on-ok="sendFunctionCode"
            :loading="isLoading">
            
            <p class="room">房间号: {{roomName}}</p>

            <Row class="room" :gutter="16">
                <Col span="12" style="display: flex">
                    <span style="line-height: 38px">被授权人姓名 :</span>
                    <Input placeholder="请输入被授权人姓名" v-model="name" style="width: 250px;margin-left: 15px"/>
                </Col>
                <Col span="12" style="display: flex">
                    <span style="line-height: 38px">被授权人电话 :</span>
                    <Input placeholder="请输入被授权人电话"  v-model="phone" style="width: 250px;margin-left: 15px"/>
                </Col>
            </Row>

            <div class="center">
                <RadioGroup v-model="codeType" type="button">
                    <Radio :label="code.value" v-for="code in codes" :key="code.value" v-if="code.value !== '08' || isShowLockCode">{{code.name}}</Radio>
                </RadioGroup>
            </div>

            <p class="beCenter">{{tip}}</p>
            <p class="beCenter">有效期: {{ codeType !== '05' ? effectiveTime : '仅能使用一次'}}</p>
        </Modal>

    </Card>
</template>

<script>
import { FunctionCode, FunctionCodeToName } from '@/libs/const'
import validate from '@/libs/validate.js'
import dayjs from 'dayjs'
import { http, api } from '@/libs/http'
export default {
  data () {
    let columns = [
      {
        title: '编号',
        align: 'center',
        key: 'id'
      },
      {
        title: '类型',
        align: 'center',
        key: 'type'
      },
      {
        title: '状态',
        align: 'center',
        key: 'status'
      },
      {
        title: '有效期',
        align: 'center',
        key: 'useful_time'
      },
      {
        title: '被授权人信息',
        align: 'center',
        key: 'licensee'
      },
      {
        title: '创建人',
        align: 'center',
        key: 'user_name'
      },
      {
        title: '创建时间',
        align: 'center',
        key: 'ctime'
      }
    ]

    return {
      codes: FunctionCode,
      type: '', // 功能码类型
      timeRange: [], // 时间区间
      show: false, // 弹唱是否打开
      roomId: '', // 房间id
      deviceId: '', // 设备id
      page: 1,
      roomName: '', // 房间名
      isLoading: false,
      codeType: '04', // 功能码类型
      tableIsLoadig: false, // 表格是否正在加载数据
      datas: [],
      columns,
      size: 10,
      FunctionCodeToName,
      name: '',
      phone: '',
      total: 0
    }
  },

  props: {
    lockInfo: {
      require: true,
      type: Object
    },
    specificModel: { // 返回D3或者门锁的具体型号，详情参考util中的sn2model方法
      type: String,
      default: ''
    }
  },

  computed: {
    effectiveTime () {
      return `${dayjs().startOf('hour').format('YYYY-MM-DD HH:mm')} - ${dayjs().startOf('hour').add(2, 'hours').format('YYYY-MM-DD HH:mm')}`
    },

    tip () {
      if (this.codeType === '08') {
        return '可在门锁上解除电子反锁状态'
      } else if (this.codeType === '04') {
        return '可用于清空管理员以外的授权密码'
      } else {
        return '可用于修改门锁时间'
      }
    },

    isShowLockCode () { // T3 D3 D3S 无电子反锁功能
      if (this.specificModel === 'T3' || this.specificModel === 'D3' || this.specificModel === 'D3S') {
        return false
      }
      return true
    }
  },

  mounted () {
    this.init()
    this.getData()
  },

  watch: {
    page () {
      this.getData()
    }
  },

  methods: {
    init () {
      const { roomId, id, roomName } = this.lockInfo
      this.roomId = roomId
      this.deviceId = id
      this.roomName = roomName
    },

    /**
        * 获取表单数据
        * @param { Boolean } isInit true => 初始化搜索 false => 按照已有的条件搜索
        */
    getData (isInit = false) {
      if (this.isInit) {
        this.page = 1
      }

      this.tableIsLoadig = true
      const params = {
        limit: this.size,
        offset: this.size * (this.page - 1)
      }

      http.request(this, api.lock_function_code_show, [this.roomId, this.deviceId], params, (res, err) => {
        if (!err) {
          this.tableIsLoadig = false

          const { count, rows } = res
          this.total = count

          this.constructorData(rows)
        }
      })
    },

    /**
        * 构造表格数据
        */
    constructorData (res) {
      this.datas = res.map(value => {
        const { ctime, id, invalid_time, type, use_time, extra: { name = '-', phone = '-', user_name = '-' } } = value

        return {
          ctime: dayjs(ctime).format('YYYY-MM-DD HH:mm'),
          useful_time: `${dayjs(invalid_time).subtract(2, 'hours').format('YYYY-MM-DD HH:mm')} 至 ${dayjs(invalid_time).format('YYYY-MM-DD HH:mm')}`,
          type: this.FunctionCodeToName[type] || '-',
          id,
          status: use_time ? '已使用' : '已下发',
          licensee: name !== '-' ? `${name} - ${phone}` : '-',
          user_name
        }
      })
    },

    /**
        * 下发功能码
        */
    sendFunctionCode () {
      if (this.name === '' || !validate.regexEnum.phone.test(this.phone)) {
        this.$Message.error('请完整填写表单数据!')
        return
      }

      this.isLoading = true

      const params = {
        type: this.codeType,
        name: this.name,
        phone: this.phone
      }

      http.request(this, api.lock_function_code_send, [this.roomId, this.deviceId], params, (res, err) => {
        if (!err) {
          this.$Message.success('功能码下发成功')
          this.isLoading = false
          this.resetData()
        }
      })
    },

    resetData () {
      this.name = ''
      this.phone = ''
      this.codeType = '04'
      this.getData()
    }
  }
}
</script>
<style lang='less' scoped>
.room {
    padding: 10px 0;
    border-bottom: 1px solid rgba(0,0,0,.2)
}

.center {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 30px 0;
}

.beCenter {
    text-align: center;
    margin-bottom: 6px;
}

.page {
    padding-bottom: 40px;
}
</style>